<?php

namespace App\Controller;

use Carbon\Carbon;
use Hyperf\Cache\Cache;
use Hyperf\Database\Model\Model;
use Swoole\Http\Request;

class Controller
{
    public $request;

    public $user;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * @return Model
     * @author xiaoze <zeasly@live.com>
     */
    public function user()
    {
        if (!$this->user) {
            $this->user = $this->guard()->user();
        }

        return $this->user;
    }

    /**
     * 获取当前登录id
     * @return int|mixed
     * @author xiaoze <zeasly@live.com>
     */
    public function userId()
    {
        return $this->user() ? $this->user()->id : 0;
    }

    /**
     * 获取guard
     * @return mixed
     * @author xiaoze <zeasly@live.com>
     */
    public function guard()
    {
        return Auth::guard();
    }

    /**
     * 回一个统一的json
     * @param int $status
     * @param string $message
     * @param null $data
     * @param int $headerStatus
     * @return \Illuminate\Http\JsonResponse
     */
    public static function jsonResponse(int $status = 1, $message = '操作成功', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = '操作成功';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return response()->json(
            ['status' => $status, 'message' => $message, 'data' => $data],
            $headerStatus,
            [],
            JSON_UNESCAPED_UNICODE
        );
    }

    public function checkRights($rights)
    {
        return true;
        $company = $this->user()->company;
        $companyRights = Rights::filterKeys($company->role ?? []);
        if (!$company || !in_array($rights, $companyRights) || $this->user()->checkRights($rights) == false) {
            throw new AuthorizationException('没有操作权限');
        }
    }
}
